package com.lottery.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lottery.entity.LotteryRecord;
import com.lottery.entity.Prize;
import com.lottery.entity.User;
import com.lottery.service.AdminService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 获取统计数据
     */
    @GetMapping("/statistics")
    public ResponseEntity<?> getStatistics() {
        Map<String, Object> stats = adminService.getStatistics();
        return ResponseEntity.ok(stats);
    }

    /**
     * 获取所有奖品
     */
    @GetMapping("/prizes")
    public ResponseEntity<?> getAllPrizes() {
        List<Prize> prizes = adminService.getAllPrizes();
        return ResponseEntity.ok(prizes);
    }

    /**
     * 创建奖品
     */
    @PostMapping("/prizes")
    public ResponseEntity<?> createPrize(@Valid @RequestBody Prize prize) {
        try {
            Prize createdPrize = adminService.createPrize(prize);
            return ResponseEntity.ok(createdPrize);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 更新奖品
     */
    @PutMapping("/prizes/{id}")
    public ResponseEntity<?> updatePrize(@PathVariable Long id, @Valid @RequestBody Prize prize) {
        try {
            Prize updatedPrize = adminService.updatePrize(id, prize);
            return ResponseEntity.ok(updatedPrize);
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 删除奖品
     */
    @DeleteMapping("/prizes/{id}")
    public ResponseEntity<?> deletePrize(@PathVariable Long id) {
        try {
            adminService.deletePrize(id);
            Map<String, String> response = new HashMap<>();
            response.put("message", "奖品删除成功");
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取奖品详情
     */
    @GetMapping("/prizes/{id}")
    public ResponseEntity<?> getPrizeById(@PathVariable Long id) {
        try {
            Prize prize = adminService.getPrizeById(id);
            return ResponseEntity.ok(prize);
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取所有抽奖记录（分页）
     */
    @GetMapping("/lottery-records")
    public ResponseEntity<?> getAllLotteryRecords(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        
        Page<LotteryRecord> records = adminService.getAllLotteryRecords(new Page<>(page + 1, size));
        return ResponseEntity.ok(records);
    }

    /**
     * 获取中奖记录
     */
    @GetMapping("/winning-records/{userId}")
    public ResponseEntity<?> getWinningRecords(@PathVariable Long userId) {
        try {
            List<LotteryRecord> records = adminService.getWinningRecords(userId);
            return ResponseEntity.ok(records);
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取所有用户
     */
    @GetMapping("/users")
    public ResponseEntity<?> getAllUsers() {
        List<User> users = adminService.getAllUsers();
        return ResponseEntity.ok(users);
    }

    /**
     * 获取用户详情
     */
    @GetMapping("/users/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Long id) {
        try {
            User user = adminService.getUserById(id);
            return ResponseEntity.ok(user);
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 为用户增加抽奖次数
     */
    @PostMapping("/users/{id}/add-chances")
    public ResponseEntity<?> addUserChances(@PathVariable Long id, @RequestBody Map<String, Integer> request) {
        try {
            int chances = request.getOrDefault("chances", 0);
            if (chances <= 0) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "抽奖次数必须大于0");
                return ResponseEntity.badRequest().body(error);
            }
            
            adminService.addUserChances(id, chances);
            Map<String, String> response = new HashMap<>();
            response.put("message", "抽奖次数添加成功");
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取指定时间范围内的抽奖记录
     */
    @GetMapping("/lottery-records/date-range")
    public ResponseEntity<?> getLotteryRecordsByDateRange(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        try {
            LocalDateTime start = LocalDateTime.parse(startDate);
            LocalDateTime end = LocalDateTime.parse(endDate);
            
            List<LotteryRecord> records = adminService.getLotteryRecordsByDateRange(start, end);
            return ResponseEntity.ok(records);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "日期格式错误或查询失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}